package com.unit.test;


import com.unit.test.controller.HelloController;
import com.unit.test.service.HelloService;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@AutoConfigureMockMvc
public class MockitoTest_v2 extends BaseTest {


    @Autowired
    MockMvc mockMvc;

    @MockBean
    HelloService helloService;


    @Test
    public void testHello() throws Exception {
        /*
        @WebMvcTest 注释告诉 Spring Boot 仅实例化 Controller 层，而不去实例化整体上下文，还可以进一步指定仅实例化 Controller 层的某个
        实例：@WebMvcTest(HelloController.class)；
        因为只实例化了 Controller 层，所以依赖的 Service 层实例需要通过 @MockBean 创建，并通过 Mockito 的方法指定 Mock 出来的 Service
        层实例在特定情况下方法调用时的返回结果。
         */
        String mockContent = "My mock content";
        Mockito.when(helloService.hello(Mockito.anyString())).thenReturn(mockContent);

        this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/spring"))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string(mockContent));
    }
}
